# 1 导入库及设置GPU
# 1.1 导入库
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
import torch.nn.functional as F
import matplotlib.pyplot as plt
from datetime import datetime
import warnings

warnings.filterwarnings("ignore")  # 忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100  # 分辨率

# 1.2 设置硬件设备，如果有GPU则使用，没有则使用cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 2 导入数据
# 2.1 数据下载
train_ds = torchvision.datasets.MNIST(
    'data',
    train=True,
    transform=torchvision.transforms.ToTensor(),
    download=True
)

test_ds = torchvision.datasets.MNIST(
    'data',
    train=False,
    transform=torchvision.transforms.ToTensor(),
    download=True
)

# 2.2 数据加载
batch_size = 32

train_dl = torch.utils.data.DataLoader(
    train_ds,
    batch_size=batch_size,
    shuffle=True
)

test_dl = torch.utils.data.DataLoader(
    test_ds,
    batch_size=batch_size
)

# 3 构建CNN网络
class Model(nn.Module):
    def __init__(self):
        super().__init__()
        # 卷积 + 池化
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=0)
        self.pool1 = nn.MaxPool2d(2, stride=2, padding=0)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=0)
        self.pool2 = nn.MaxPool2d(2, stride=2, padding=0)

        # 展平
        self.fc1 = nn.Linear(1600, 64)
        self.fc2 = nn.Linear(64, 10)

    # 前向传播
    def forward(self, x):
        # 卷积池化1
        x = self.conv1(x)
        x = F.relu(x)
        x = self.pool1(x)
        # 卷积池化2
        x = self.conv2(x)
        x = F.relu(x)
        x = self.pool2(x)
        # 展平
        x = torch.flatten(x, start_dim=1)
        # 全连接层1
        x = self.fc1(x)
        x = F.relu(x)
        # 输出层
        x = self.fc2(x)

        return x

# 4 模型训练
# 4.1 模型选择
model = Model().to(device)

# 4.2 损失函数(交叉熵)
loss_fn = nn.CrossEntropyLoss()

# 4.3 优化器
opt = torch.optim.SGD(model.parameters(), lr=1e-2)

# 4.4 训练函数
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)   # 训练集的大小
    num_batches = len(dataloader)    # 批次数目

    # 初始化训练损失和正确率
    train_loss = 0
    train_acc = 0

    # 获取图片和标签
    for X, y in dataloader:
        X = X.to(device)
        y = y.to(device)

        # 计算预测误差
        pred = model(X)
        loss = loss_fn(pred, y)

        # 反向传播
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # 记录acc和loss
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc /= size
    train_loss /= num_batches

    return train_acc, train_loss

# 4.5 测试函数
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)

    test_loss = 0
    test_acc = 0

    # 当不进行训练时，停止梯度训练，节省计算资源内耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            # 计算loss
            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

        test_acc /= size
        test_loss /= num_batches

        return test_acc, test_loss

# 5 正式训练
epochs     = 5
train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%，Test_loss:{:.3f}')
    print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss))


# 6 结果可视化
current_time = datetime.now()   # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))   # 新建画布，宽 12 英寸、高 3 英寸

# 左图：Accuracy
plt.subplot(1, 2, 1)   # 把画布分成 1 行 2 列的子图，激活第 1 个子图（左图）
# 在左图上画两条曲线：训练准确率、测试准确率。默认连续折线
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')   # 显示图例，放在左图的右下角
plt.title('Training and Test Accuracy')   # 左图标题

# 右图：Loss
plt.subplot(1, 2, 2)   # 激活第 2 个子图（右图）
# 右图画训练/测试损失曲线
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')   # 右图图例放在右上角
plt.title('Training and Test Loss')   # 右图标题

plt.show()

























